/*
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-05 15:06:39
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-02-06 09:50:05
 * @FilePath: \asset-management-webc:\Users\21776\Desktop\毕设\shop_app_vue3\store\userStore.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//用户信息
import { defineStore } from 'pinia';
import {
  login,
  wxLogin,
  getUserInfo,
  verifyToken,
  updatePhone,
  updateBirthday,
  updateNickname,
  updateAvatar,
  updateGender,
  updateEmail,
  updateIpLocation
} from '../api/login.js';

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    // token
    token: localStorage.getItem('token') || null,
    // 加载状态
    loading: {
      login: false,
      info: false,
      update: false
    }
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    // 获取加载状态
    isLoading: (state) => (type) => state.loading[type]
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      if (userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
      } else {
        localStorage.removeItem('userInfo');
      }
    },

    // 设置token
    setToken(token) {
      this.token = token;
      if (token) {
        localStorage.setItem('token', token);
      } else {
        localStorage.removeItem('token');
      }
    },

    // 清除用户信息
    clearUserInfo() {
      this.userInfo = null;
      this.token = null;
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
    },

    // 普通登录
    async loginByPassword(loginData) {
      if (this.loading.login) return;
      
      try {
        this.loading.login = true;
        const res = await login(loginData);
        if (res.code === 0) {
          this.setToken(res.data.token);
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      } finally {
        this.loading.login = false;
      }
    },

    // 微信登录
    async loginByWechat(code) {
      if (this.loading.login) return;
      
      try {
        this.loading.login = true;
        const res = await wxLogin(code);
        if (res.code === 0) {
          this.setToken(res.data.token);
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('微信登录失败:', error);
        throw error;
      } finally {
        this.loading.login = false;
      }
    },

    // 加载用户信息
    async loadUserInfo() {
      if (this.loading.info) return;
      
      try {
        this.loading.info = true;
        const res = await getUserInfo();
        if (res.code === 0) {
          this.setUserInfo(res.data);
        }
        return res;
      } catch (error) {
        console.error('加载用户信息失败:', error);
        throw error;
      } finally {
        this.loading.info = false;
      }
    },

    // 验证token
    async verifyToken() {
      if (!this.token) return false;
      
      try {
        const res = await verifyToken();
        return res.code === 0;
      } catch (error) {
        console.error('验证token失败:', error);
        this.clearUserInfo();
        return false;
      }
    },

    // 更新用户手机号
    async updatePhone(phone) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updatePhone(phone);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新手机号失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户生日
    async updateBirthday(birthday) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateBirthday(birthday);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新生日失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户昵称
    async updateNickname(nickname) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateNickname(nickname);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新昵称失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户头像
    async updateAvatar(avatarUrl) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateAvatar(avatarUrl);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新头像失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户性别
    async updateGender(gender) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateGender(gender);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新性别失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户邮箱
    async updateEmail(email) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateEmail(email);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新邮箱失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    },

    // 更新用户IP属地
    async updateIpLocation(ipLocation) {
      if (this.loading.update) return;
      
      try {
        this.loading.update = true;
        const res = await updateIpLocation(ipLocation);
        if (res.code === 0) {
          await this.loadUserInfo();
        }
        return res;
      } catch (error) {
        console.error('更新IP属地失败:', error);
        throw error;
      } finally {
        this.loading.update = false;
      }
    }
  }
});
